/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.bonbhel.oracle.auctionApp.resource;

import com.bonbhel.oracle.auctionApp.Seller;
import java.util.Collection;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.DELETE;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.QueryParam;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.WebApplicationException;
import javax.persistence.NoResultException;
import javax.persistence.EntityManager;
import java.util.List;
import com.bonbhel.oracle.auctionApp.Item;
import com.bonbhel.oracle.auctionApp.converter.SellerConverter;
import javax.ejb.Stateless;

/**
 *
 * @author bonbhejf
 */

@Stateless
public class SellerResource {
    @javax.ejb.EJB
    private ItemsResourceSub itemsResourceSub;
    @Context
    protected UriInfo uriInfo;
    protected EntityManager em;
    protected Long id;
  
    /** Creates a new instance of SellerResource */
    public SellerResource() {
    }

    public void setId(Long id) {
        this.id = id;
    }

    public void setEm(EntityManager em) {
        this.em = em;
    }

    /**
     * Get method for retrieving an instance of Seller identified by id in XML format.
     *
     * @param id identifier for the entity
     * @return an instance of SellerConverter
     */

    @GET
    @Produces({"application/json"})
    public SellerConverter get(@QueryParam("expandLevel")
                               @DefaultValue("1")
    int expandLevel) {
        return new SellerConverter(getEntity(), uriInfo.getAbsolutePath(), expandLevel);
    }

    /**
     * Put method for updating an instance of Seller identified by id using XML as the input format.
     *
     * @param id identifier for the entity
     * @param data an SellerConverter entity that is deserialized from a XML stream
     */
    @PUT
    @Consumes({"application/xml", "application/json"})
    public void put(SellerConverter data) {
        updateEntity(getEntity(), data.resolveEntity(em));
    }

    /**
     * Delete method for deleting an instance of Seller identified by id.
     *
     * @param id identifier for the entity
     */
    @DELETE
    public void delete() {
        deleteEntity(getEntity());
    }

    /**
     * Returns an instance of Seller identified by id.
     *
     * @param id identifier for the entity
     * @return an instance of Seller
     */
    protected Seller getEntity() {
        try {
            return (Seller) em.createQuery("SELECT e FROM Seller e where e.id = :id").setParameter("id", id).getSingleResult();
        } catch (NoResultException ex) {
            throw new WebApplicationException(new Throwable("Resource for " + uriInfo.getAbsolutePath() + " does not exist."), 404);
        }
    }

    /**
     * Updates entity using data from newEntity.
     *
     * @param entity the entity to update
     * @param newEntity the entity containing the new data
     * @return the updated entity
     */
    private Seller updateEntity(Seller entity, Seller newEntity) {
        List<Item> items = entity.getItems();
        List<Item> itemsNew = newEntity.getItems();
        entity = em.merge(newEntity);
        for (Item value : items) {
            if (!itemsNew.contains(value)) {
                throw new WebApplicationException(new Throwable("Cannot remove items from items"));
            }
        }
        for (Item value : itemsNew) {
            if (!items.contains(value)) {
                Seller oldEntity = value.getSeller();
                value.setSeller(entity);
                if (oldEntity != null && !oldEntity.equals(entity)) {
                    oldEntity.getItems().remove(value);
                }
            }
        }
        return entity;
    }

    /**
     * Deletes the entity.
     *
     * @param entity the entity to deletle
     */
    private void deleteEntity(Seller entity) {
        if (!entity.getItems().isEmpty()) {
            throw new WebApplicationException(new Throwable("Cannot delete entity because items is not empty."));
        }
        em.remove(entity);
    }

    /**
     * Returns a dynamic instance of ItemsResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of ItemsResource
     */
    @Path("items/")
    public ItemsResource getItemsResource() {
        itemsResourceSub.setParent(getEntity());
        return itemsResourceSub;
    }

    @Stateless(name = "SellerResource.ItemsResourceSub")
    public static class ItemsResourceSub extends ItemsResource {

        private Seller parent;

        public void setParent(Seller parent) {
            this.parent = parent;
        }

        @Override
        protected Collection<Item> getEntities(int start, int max, String query) {
            Collection<Item> result = new java.util.ArrayList<Item>();
            int index = 0;
            for (Item e : parent.getItems()) {
                if (index >= start && (index - start) < max) {
                    result.add(e);
                }
                index++;
            }
            return result;
        }
    }
}
